package top.someapp.applib.kits;

import android.os.Build;
import androidx.annotation.NonNull;
import top.someapp.applib.AndroidVersion;

/**
 * android版本判断工具类
 *
 * @author zwz
 * Created on 2020-03-30
 */
public class Versions {

    public static final boolean IS_GE_ANDROID_6 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    public static final boolean IS_GE_ANDROID_8 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
    public static final boolean IS_GE_ANDROID_9 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P;
    public static final boolean IS_GE_ANDROID_10 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
    private static AndroidVersion _current;

    private Versions() {
        // no need instance.
    }

    public static AndroidVersion current() {
        if (_current == null) {
            int sdkInt = Build.VERSION.SDK_INT;
            AndroidVersion[] versions = AndroidVersion.values();
            int min = 0;
            int max = versions.length;
            int mid;
            for (; ; ) {
                mid = (min + max) / 2;
                int code = versions[mid].code;
                if (code == sdkInt) {
                    break;
                } else if (code < sdkInt) {
                    min = mid;
                } else {
                    max = mid;
                }
            }
            _current = versions[mid];
        }
        return _current;
    }

    public static boolean is(@NonNull AndroidVersion target) {
        return current() == target;
    }

    public static boolean isGE(@NonNull AndroidVersion target) {
        return current().code >= target.code;
    }

    public static boolean isGT(@NonNull AndroidVersion target) {
        return current().code > target.code;
    }

    public static boolean isLE(@NonNull AndroidVersion target) {
        return current().code <= target.code;
    }

    public static boolean isLT(@NonNull AndroidVersion target) {
        return current().code < target.code;
    }

    public static boolean isAndroid6() {
        return Booleans.trueTrue(isGE(AndroidVersion.M), isLT(AndroidVersion.N));
    }

    public static boolean isAndroid7() {
        return Booleans.trueTrue(isGE(AndroidVersion.N), isLT(AndroidVersion.O));
    }

    public static boolean isAndroid8() {
        return Booleans.trueTrue(isGE(AndroidVersion.O), isLT(AndroidVersion.P));
    }

    public static boolean isAndroid9() {
        return Booleans.trueTrue(isGE(AndroidVersion.P), isLT(AndroidVersion.Q));
    }
}
